import { Request, handleFileInUploading } from '../../../utils/util'
// 系统信息
const App = getApp()

// 当前展示的图片实际大小
// 裁剪后还可以继续裁剪
let imageWidth = 0
let imageHeight = 0
// 以下为裁剪框缩放时临时变量
// 当前操作的缩放角
let activeCorner = ''
// 裁剪框缩放前的位置信息
let clipBoxBeforeScaleClipX = 0
let clipBoxBeforeScaleClipY = 0
// 裁剪框缩放前的宽高
let clipBoxBeforeScaleWidth = 0
let clipBoxBeforeScaleHeight = 0
// 裁剪框缩放前点击鼠标的Page(X|Y)位置信息
let clipBoxBeforeScalePageX = 0
let clipBoxBeforeScalePageY = 0

// 以下为裁剪框移动时临时变量
// 裁剪框移动鼠标内部位置信息
let clipBoxMoveInnerX = 0
let clipBoxMoveInnerY = 0

// 图片在窗口面板尺寸小的缩放比
let xScale = 1
let yScale = 1
Page({
    data: {
        // 当前图片路径
        imagePath: '',

        originWidth: 0,
        originHeight: 0,
        // 图片显示面板宽高
        panelWidth: 0,
        panelHeight: 0,

        // 裁剪区域宽高
        clipWidth: 0,
        clipHeight: 0,
        // 裁剪区域位置信息
        clipX: 0,
        clipY: 0,
        // 裁剪区域底图位置信息
        clipImgX: 0,
        clipImgY: 0,

        // 正要裁剪的宽高
        croppingImageWidth: 0,
        croppingImageHeight: 0,

        loading:true
    },
    onLoad(option) {
        this.loadImage(option.avatar)
    },
    onReady(){
        this.setData({loading:false})
    },

    loadImage(originPath) {
        console.log("chooseImg", originPath)
        let _this = this

        wx.getImageInfo({
            src: originPath,
            success: function (res) {
                _this.setData({
                    originWidth: res.width,
                    originHeight: res.height
                })
                _this.initImage(res.width, res.height, originPath)
            },
            fail: function (err) {
                console.log(err)
            }
        })
    },
    initImage(imgWidth, imgHeight, imagePath) {
        console.log("init Image")
        this.setData({
            clipX: 0,
            clipY: 0,
            clipImgX: 0,
            clipImgY: 0
        })

        // 初始化图片，根据窗口大小，设置图片面板尺寸
        let panelW = App.globalData.windowWidth - 20
        let panelH = App.globalData.windowHeight - 100
        if (panelH / panelW >= imgHeight / imgWidth) {
            panelH = parseInt(panelW * imgHeight / imgWidth)
        } else {
            panelW = parseInt(panelH * imgWidth / imgHeight)
        }
        imageWidth = imgWidth
        imageHeight = imgHeight

        xScale = panelW / imageWidth
        yScale = panelH / imageHeight

        this.setData({
            imagePath,
            panelWidth: panelW,
            panelHeight: panelH,
            clipWidth: panelW,
            clipHeight: panelW,
            croppingImageWidth: imgWidth,
            croppingImageHeight: imgWidth
        })
        console.log("data", this.data)
    },
    touchstartM(event) {
        const { clipX, clipY } = this.data
        const { pageX, pageY } = event.touches[0]
        // 获取鼠标点在裁剪框的内部位置信息
        clipBoxMoveInnerX = pageX - clipX
        clipBoxMoveInnerY = pageY - clipY
    },
    touchmoveM(event) {
        console.log("moveM")
        const { pageX, pageY } = event.touches[0]
        const { panelWidth, panelHeight, clipWidth } = this.data
        const clipHeight = clipWidth
        // 裁剪框不能脱离面板
        // X位置范围为 0 到 (面板宽度-裁剪框宽度)
        let clipX = pageX - clipBoxMoveInnerX
        clipX = Math.max(clipX, 0)
        const panelX = panelWidth - clipWidth
        clipX = Math.min(clipX, panelX)
        // Y位置范围为 0 到 (面板高度-裁剪框高度)
        let clipY = pageY - clipBoxMoveInnerY
        clipY = Math.max(clipY, 0)
        const panleY = panelHeight - clipHeight
        clipY = Math.min(clipY, panleY)

        // 裁剪框底图位置信息
        const clipImgX = 0 - clipX
        const clipImgY = 0 - clipY

        this.setData({
            clipX,
            clipY,
            clipImgX,
            clipImgY
        })
    },

    // 处理缩放动作中不同corner时的尺寸位置信息
    getClipX(clipWidth) {
        switch (activeCorner) {
            case 'leftTop':
            case 'leftBottom':
                return clipBoxBeforeScaleClipX + (clipBoxBeforeScaleWidth - clipWidth)
            case 'rightTop':
            case 'rightBottom':
                return clipBoxBeforeScaleClipX;
            default:
                return 0
        }
    },
    getClipY(clipHeight) {
        switch (activeCorner) {
            case 'leftTop':
            case 'rightTop':
                return clipBoxBeforeScaleClipY + (clipBoxBeforeScaleHeight - clipHeight)
            case 'leftBottom':
            case 'rightBottom':
                return clipBoxBeforeScaleClipY
            default:
                return 0
        }
    },
    getScaleXWidthOffset(offsetW) {
        switch (activeCorner) {
            case 'leftTop':
            case 'leftBottom':
                return -offsetW
            case 'rightTop':
            case 'rightBottom':
                return offsetW
            default:
                return 0
        }
    },
    getScaleYHeightOffset(offsetH) {
        switch (activeCorner) {
            case 'rightBottom':
            case 'leftBottom':
                return offsetH
            case 'rightTop':
            case 'leftTop':
                return -offsetH
            default:
                return 0
        }
    },

    touchstart(event) {
        console.log("touch start")
        const dragId = event.currentTarget.dataset.id
        const { pageX, pageY } = event.touches[0]
        const { clipX, clipY, clipHeight, clipWidth } = this.data

        // 设置缩放时临时变量初始化值
        activeCorner = dragId
        clipBoxBeforeScalePageX = pageX
        clipBoxBeforeScalePageY = pageY
        clipBoxBeforeScaleClipX = clipX
        clipBoxBeforeScaleClipY = clipY
        clipBoxBeforeScaleWidth = clipWidth
        clipBoxBeforeScaleHeight = clipHeight
    },
    touchmove(event) {
        console.log("touchtranslation")
        const { pageX, pageY } = event.touches[0]
        const { panelWidth, panelHeight } = this.data

        // 缩放在X上的偏移
        const xWidthOffset = this.getScaleXWidthOffset(pageX - clipBoxBeforeScalePageX)
        // 裁剪框最小宽度36
        let clipWidth = Math.max(clipBoxBeforeScaleWidth + xWidthOffset, 36)
        // 设置缩放最大宽度，放大时不能超过面板、缩小时不能超过初始裁剪框
        let tempPanelWidth = pageX > clipBoxBeforeScalePageX ? panelWidth - clipBoxBeforeScaleClipX : clipBoxBeforeScaleWidth + clipBoxBeforeScaleClipX
        // 设置裁剪框宽度
        clipWidth = Math.min(clipWidth, tempPanelWidth)

        // 缩放在Y上的偏移
        const yHeightOffset = this.getScaleYHeightOffset(pageY - clipBoxBeforeScalePageY)
        // 裁剪框最小高度36
        let clipHeight = Math.max(clipBoxBeforeScaleHeight + yHeightOffset, 36)
        // 设置缩放最大高度，放大时不能超过面板、缩小时不能超过初始裁剪框
        let tempPanelHeight = pageY > clipBoxBeforeScalePageY ? panelHeight - clipBoxBeforeScaleClipY : clipBoxBeforeScaleHeight + clipBoxBeforeScaleClipY
        // 设置裁剪框高度
        clipHeight = Math.min(clipHeight, tempPanelHeight)
        let clipLen = Math.min(clipHeight, clipWidth)
        // 裁剪框位置信息
        let clipX = this.getClipX(clipLen)
        let clipY = this.getClipY(clipLen)
        // 裁剪框底图位置信息
        let clipImgX = 0 - clipX
        let clipImgY = 0 - clipY
        this.setData({
            clipWidth: clipLen,
            clipHeight: clipLen,
            clipX,
            clipY,
            clipImgX,
            clipImgY,
            croppingImageWidth: parseInt(clipLen / xScale),
            croppingImageHeight: parseInt(clipLen / yScale)
        })
        console.log(clipWidth, clipHeight)
    },
    async cropperImage() {

    },

    setAvatar() {
        // const symbol = await getStockSymbol(name);
        const stockPrice = "00"
        const { imagePath, croppingImageWidth, croppingImageHeight, panelHeight, panelWidth, clipImgX, clipImgY } = this.data
        let preCtx = wx.createCanvasContext('main')
        preCtx.clearRect(0, 0, imageWidth, imageHeight)

        const width = croppingImageWidth
        const height = croppingImageWidth
        const xPos = Math.abs(clipImgX / xScale)
        const yPos = Math.abs(clipImgY / yScale)

        preCtx.drawImage(imagePath, xPos, yPos, width, height, 0, 0, width, height)
        preCtx.save()
        preCtx.restore()
        let path
        preCtx.draw(false, function () {
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width,
                height,
                destWidth: width,
                destHeight: height,
                canvasId: 'main',
                success: (canRes) => {
                    path = canRes.tempFilePath
                    let timestamp = new Date().getTime();
                    // timestamp="1685452054987"
                    let imgType = path.split('.')[1]
                    let imgName = `avatar/${timestamp}.${imgType}`
                    handleFileInUploading(imgName, path)
                    console.log("type", path.split('.'))
                    let url = `https://seubilibili-1300357628.cos.ap-nanjing.myqcloud.com/${imgName}`
                    Request({
                        url: '/updateuser',
                        method: 'post',
                        data: {
                            field: "avatar",
                            value: url
                        }
                    }).then(res => {
                        if (res.success) {
                            wx.showToast({
                                title: '修改头像成功',//提示文字
                                duration: 1000,//显示时长
                                mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
                                icon: 'success', //图标，支持"success"、"loading"  
                                success: function () {
                                    setTimeout(function () {
                                        wx.reLaunch({
                                            url: '/pages/home/home'
                                        });
                                    }, 1000)

                                },//接口调用成功
                                fail: function () { },  //接口调用失败的回调函数  
                                complete: function () { } //接口调用结束的回调函数  
                            })
                        }
                    }).catch(error => {
                        console.log(error);
                    });
                }
            })
            return "0000"
        })
    }
})
